//
//  CSYComposePageViewController.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/19.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

import SnapKit

import SVProgressHUD

private var flag = true

class CSYComposePageViewController: UIViewController {
    
    //底部工具条::用户点击了表情键盘按钮
    
    private lazy var keyboardView : CSYEmoticonKeyboardView = CSYEmoticonKeyboardView { (model) -> () in
        
        self.textView.insertTextAttachment(model)
        
    }
    
    @objc private func showEmoticonKeyboard(){
        
        //如果是默认键盘,键盘的inputView是nil
        textView.resignFirstResponder()
        
        textView.inputView = (textView.inputView == nil ? keyboardView : nil)

        textView.becomeFirstResponder()
        
    }
    //底部工具条::用户点击了添加图片的时候的方法
    @objc private func selectPicture(){
    
        if flag{
        
            flag = false
            
            print("用户点击发布图片按钮")
            
            view.bringSubviewToFront(toolBar)
            
            view.endEditing(true)
            
            pictureSelectorView.view.snp_updateConstraints { (make) -> Void in
                
                make.height.equalTo(screen_Height * 2 / 3)
                
            }
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.layoutIfNeeded()
                
                }) { (_) -> Void in
                    
                    print("准备选择图片")
                    
            }
            
        }else{
            
            flag = true
        
            print("用户取消发布图片")
        
            pictureSelectorView.view.snp_updateConstraints { (make) -> Void in
                
                make.height.equalTo(0)
                
            }
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.layoutIfNeeded()
                
                }) { (_) -> Void in
                    
                    print("取消选择图片")
                    
            }
        
        }
    }
    
    //响应发布和取消的按钮的点击方法
    @objc private func close(){
    
        print("点击了关闭按钮")
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    
    }
    
    @objc private func send(){
    
        print("点击了发布按钮")
        
        guard let token = GetUserInfoModel().userToken else{
            
            SVProgressHUD.showErrorWithStatus("您还没有登陆", maskType: SVProgressHUDMaskType.Black)
            
            return
            
        }
        
        let urlString : String = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let paramaters : [String : AnyObject]? = ["access_token" : token , "status" : textView.emoticonToString()]
        
        //使用AFN封装的图片二进制参数传递请求(POST)来发布图片
        
        if pictureSelectorView.pictureBox.count >= 1 {
            
            let picData : NSData = UIImagePNGRepresentation(pictureSelectorView.pictureBox[0])!
            
            NetworkTools.shareNetWorkTools.uploadPicture(picData, urlStr: urlString, parameters: paramaters, finishedBlock: { (result, error) -> () in
                
                if error != nil {
                    
                    print("发布失败")
                    
                    print(error)
                    
                }
                
                UIView.animateWithDuration(0.75, animations: { () -> Void in
                    
                    SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Clear)
                    
                    }, completion: { (_) -> Void in
                        
                        SVProgressHUD.dismiss()
                        
                        self.dismissViewControllerAnimated(true, completion: { () -> Void in
                            
                            print("发布成功")
                            
                            print(result)
                            
                        })
                })
                
            })
            
            
        }
        
        
        if pictureSelectorView.pictureBox.count == 0{
        
            //使用POST请求发送文字微博
            
            NetworkTools.shareNetWorkTools.requiredJsonValueToDictionary(AFNSESSION_TYPE.POST, urlStr: urlString, parameters: paramaters) { (result, error) -> () in
                
                if error != nil {
                    
                    print("发布失败")
                    
                    print(error)
                    
                }
                
                UIView.animateWithDuration(0.75, animations: { () -> Void in
                    
                    SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Clear)
                    
                    }, completion: { (_) -> Void in
                        
                        SVProgressHUD.dismiss()
                        
                        self.dismissViewControllerAnimated(true, completion: { () -> Void in
                            
                            print("发布成功")
                            
                            print(result)
                            
                        })
                })
                
            }
            
        }
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
    
        setNavBarItem()
        
        setTextView()
        
        setToolBar()
        
        resignNotice()
        
        setPictureSelector()
        
        
        
        // Do any additional setup after loading the view.
    }
    
    private func resignNotice(){
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardFrameChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
        
    }
    
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //懒加载所有控件
    lazy var placeHolderLabel : UILabel = UILabel(textInfo: "分享你妹啊...", fontSize: 20, infoColor: UIColor.darkGrayColor(), numberOFLines: 1, alphaValue: 1, margin: 0)

    lazy var toolBar : UIToolbar = UIToolbar()
    
    lazy var textView : CSYTextSettingView = {
    
        let view : CSYTextSettingView = CSYTextSettingView()
        
        view.backgroundColor = UIColor(white: 0.94, alpha: 1)
        
        view.font = UIFont.systemFontOfSize(18)
        
        view.textColor = UIColor.darkGrayColor()

        view.delegate = self
        
        view.alwaysBounceVertical = true
        
        view.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return view
        
    }()
    
//    lazy var pictureSelectorView : CSYPictureSeletedViewController = CSYPictureSeletedViewController()
    
    lazy var pictureSelectorView : CSYPictureSeletedViewController = CSYPictureSeletedViewController()
    
}

extension CSYComposePageViewController {

    //根据键盘更改ToolBar的Frame
    @objc private func keyBoardFrameChanged(notice : NSNotification) {
    
        print("键盘响应事件")
        
        //取消图片的选择
        flag = false
        
        selectPicture()
        
//        print(notice)
    
        let animationTime = notice.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        let endFrame = (notice.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let cuval = notice.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSInteger
        
        
        
        //修改ToolBar的高度约束
        let toolBarOffset = -screen_Height + endFrame.origin.y
        
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(toolBarOffset)
            
        }
        
        UIView.animateWithDuration(animationTime, animations: { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: cuval)!)
            
            self.view.layoutIfNeeded()
            
            })
        
    }

    @objc private func keyBoardWillHide(notice : NSNotification){
    
        print("键盘将要消失了")
        
        flag = true
        
        selectPicture()
    
    }
    
    

}

//设置发布微博框内选中TextView的操作
extension CSYComposePageViewController : UITextViewDelegate{

    //当文本框的值改变之后
    func textViewDidChangeSelection(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }


}


//设置UI的分类
extension CSYComposePageViewController{
    
    private func setPictureSelector(){
    
        
        //问题:为什么要添加子控制器
        addChildViewController(pictureSelectorView)
        
        view.addSubview(pictureSelectorView.view)
        
        pictureSelectorView.view.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(view)
            
            make.height.equalTo(0)
            
        }
        
    }

    private func setTextView(){
    
        view.addSubview(textView)
        
        view.layoutIfNeeded()
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.left.right.top.equalTo(self.view)
            
            make.height.equalTo(view.bounds.height / 3)
            
        }
        
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(textView.snp_left).offset(5)
            
            make.top.equalTo(textView.snp_top).offset(8)
            
        }
    
    }
    
    private func setToolBar(){
    
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.bottom.right.equalTo(view)
            
            make.height.equalTo(40)
            
        }
        

        
        var items : [UIBarButtonItem] = [UIBarButtonItem]()
        
        let itemDict = [["imageName": "compose_toolbar_picture" , "actionName" : "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background" , "actionName" : "showEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemDict{
        
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            
//            let item2 = UIBarButtonItem(image: UIImage(named: "compose_toolbar_picture"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        
            items.append(item)
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(space)
            
        }
        
        items.removeLast()

        print(items)
        
        toolBar.items = items
        
        print(toolBar.items)
        
    }

    private func setNavBarItem(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRectMake(0,0,200,45))
        
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(textInfo: "发布微博", fontSize: 14, infoColor: UIColor.darkGrayColor(), numberOFLines: 1, alphaValue: 1, margin: 0)
        
        let nameLabel = UILabel(textInfo: GetUserInfoModel().userName ?? "", fontSize: 12, infoColor: UIColor.lightGrayColor(), numberOFLines: 1, alphaValue: 1, margin: 0)
        
        titleView.addSubview(titleLabel)
        
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in

            make.top.equalTo(titleView.snp_top).offset(5)
            
            make.centerX.equalTo(titleView.snp_centerX)
            
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(titleLabel.snp_bottom).offset(2)
            
            make.centerX.equalTo(titleLabel.snp_centerX)
            
        }
        
        
    }
    
    
    
    

}
